package com.hontech.bv.codec

private val HEX_LIST = arrayOf(
    '0', '1', '2', '3',
    '4', '5', '6', '7',
    '8', '9', 'a', 'b',
    'c', 'd', 'e', 'f'
)

fun Byte.toUint8() = this.toInt() and 0xFF

fun ByteArray.xorSum(offset: Int, len: Int): Int {
    var s = 0
    for (i in 0 until len) {
        val item = this[i + offset].toUint8()
        s = s xor item
    }
    return s
}

fun Int.toHex4(): String {
    val h0 = (this shr 12) and 0x0F
    val h1 = (this shr 8) and 0x0F
    val h2 = (this shr 4) and 0x0F
    val h3 = this and 0x0F
    return "${HEX_LIST[h0]}${HEX_LIST[h1]}${HEX_LIST[h2]}${HEX_LIST[h3]}"
}

fun ByteArray.toHex(offset: Int = 0, len: Int = size - offset): String {
    val arr = CharArray(len * 3)
    for (i in 0 until len) {
        val value = this[i + offset].toUint8()
        val c0 = HEX_LIST[ value shr 4 ]
        val c1 = HEX_LIST[ value and 0x0F ]
        arr[i * 3 + 0] = c0
        arr[i * 3 + 1] = c1
        arr[i * 3 + 2] = ' '
    }
    return String(arr)
}

fun ByteArray.toMacStr(): String {
    val arr = CharArray(size * 3 - 1)
    for (i in indices) {
        val value = this[i].toUint8()
        val c0 = HEX_LIST[ value shr 4 ]
        val c1 = HEX_LIST[ value and 0x0F ]
        arr[i * 3 + 0] = c0
        arr[i * 3 + 1] = c1
        if (i == (size - 1)) {
            break
        }
        arr[i * 3 + 2] = ':'
    }
    return String(arr)
}


